package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;

    /**
     * 菜品保存方法
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public void save(DishDto dishDto) {
        dishDto.setCreateTime(LocalDateTime.now());
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setSort(0);
        dishDto.setStatus(1);//不禁售

        dishMapper.save(dishDto);

        List<DishFlavor> flavors = dishDto.getFlavors();
       /* for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
            flavor.setUpdateUser(dishDto.getUpdateUser());
            flavor.setCreateUser(dishDto.getCreateUser());
            flavor.setUpdateTime(LocalDateTime.now());
            flavor.setCreateTime(LocalDateTime.now());*/
            flavors= flavors.stream().map(flavor ->{
               flavor.setDishId(dishDto.getId());
               flavor.setUpdateUser(dishDto.getUpdateUser());
               flavor.setCreateUser(dishDto.getCreateUser());
               flavor.setUpdateTime(LocalDateTime.now());
               flavor.setCreateTime(LocalDateTime.now());
                   return  flavor;
    }).collect(Collectors.toList());
        dishFlavorMapper.saveBatch(flavors);

        }

    /**
     * 分页查询菜品信息
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<DishDto> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<DishDto> dishDtoList = dishMapper.findByPage();

        PageInfo<DishDto>dishDtoPageInfo=new PageInfo<>(dishDtoList);

        Page<DishDto> dishDtoPage =new Page<>();
        dishDtoPage.setTotal(dishDtoPageInfo.getTotal());
        dishDtoPage.setRecords(dishDtoPageInfo.getList());
        return dishDtoPage;

    }

    /**
     * 根据菜品id查询一个菜品和对应多条口味记录数据
     *
     * @param id
     * @return
     */
    @Override
    public DishDto findById(long id) {
        return dishMapper.findById(id);
    }

    /**
     * 更新菜品数据
     *
     * @param dishDto
     */
    @Override
    public void update(DishDto dishDto) {
        dishDto.setUpdateTime(LocalDateTime.now());

        dishMapper.updateById(dishDto);

        dishFlavorMapper.deleteByDishId(dishDto.getId());

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setUpdateUser(dishDto.getUpdateUser());
            flavor.setUpdateTime(dishDto.getUpdateTime());
            if (flavor.getId()==null){
                flavor.setDishId(dishDto.getId());
                flavor.setUpdateUser(dishDto.getUpdateUser());
                flavor.setCreateUser(dishDto.getCreateUser());
                flavor.setUpdateTime(LocalDateTime.now());
                flavor.setCreateTime(LocalDateTime.now());
            }
        }
        dishFlavorMapper.saveBatch(flavors);
    }

    /**
     * 根据id删除菜品
     *
     * @param id
     */
//    @Override
//    public void deleteById(long id) {
//      //  Integer byCid = dishMapper.findByCid(id);
//        dishMapper.deleteById(id);
//    }
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    /**
     * 根据类别id查询菜品列表
     *
     * @param cid
     * @return
     */
    @Override
    public List<DishDto> findAllByCid(Long cid,Integer status) {
        //1.查询了菜品列表（每个菜品没有包含口味列表）
        List<Dish> dishList = dishMapper.findAllByCid(cid,status);

        //项查询菜品的时候同时查询口味列表有2种做法：
        //第一种：sql语句进行多表查询映射，菜品表与口味表多表查询
        //第二种：先查询菜品列表，遍历，根据每个菜品id查询口味列表，最后将菜品与口味都封装DishDto中（本次使用）

        //2.定义DishDto列表集合接收所有菜品及其菜品的口味
        List<DishDto> dishDtoList = new ArrayList<>();

        //3.遍历dishList菜品列表
        dishDtoList =  dishList.stream().map(dish -> {
            //根据菜品id查询口味列表
            List<DishFlavor> dishFlavorList = dishFlavorMapper.findAllByDishId(dish.getId());
            //封装到DishDto
            DishDto dishDto = new DishDto();
            dishDto.setFlavors(dishFlavorList);
            //将dish对象中所有属性数据赋值给dishDto的属性数据
            BeanUtils.copyProperties(dish,dishDto);
            //根据类别id查询类别对象
            Category category = categoryMapper.findByCid(cid);
            //封装类别名称到DishDto
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());

        return dishDtoList;
    }

    /**
     * 批量删除菜品
     *
     * @param ids 菜品id
     * @param opr
     */
    @Override
    @Transactional
    public void deleteByIds(List<Long> ids, long opr) {
        Integer count = dishMapper.findByIds(ids);
        if (count>0){
            throw new BusinessException("存在在售的商品,请先停售");
        }
         dishMapper.deleteByIds(ids,opr,LocalDateTime.now());
        dishFlavorMapper.deleteDishFlavorByIds(ids,opr,LocalDateTime.now());
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
//    @Override
//   @Transactional
//    public void deleteByIds(Long[] ids, Long updateUser, LocalDateTime updateTime) {
//
//        Long count = dishMapper.findByIds(ids);
//
//        if (count>1){
//            throw new BusinessException("存在在售的商品,请先停售");
//        }
//        dishMapper.deleteByIds(ids,updateUser,LocalDateTime.now());
//
//      //  dishFlavorMapper.deleteDishFlavorByIds(ids,updateUser,LocalDateTime.now());
//    }

    /**
     * 3(批量停售)
     *
     * @param ids
     * @param opr
     */
    @Override
    public void updateStatusFByIds(List<Long> ids, long opr) {
        dishMapper.updateStatusFByIds(ids,opr,LocalDateTime.now());
    }

    /**
     * 修改菜品的状态(批量起售)
     *
     * @param ids
     * @param opr
     */
    @Override
    public void updateStatusTByIds(List<Long> ids, long opr) {
        dishMapper.updateStatusTByIds(ids,opr,LocalDateTime.now());

    }


}

